package com.wenfs.demo.util.shiro;

import com.wenfs.demo.entity.SysUser;
import com.wenfs.demo.service.ISysMenu;
import com.wenfs.demo.service.ISysRole;
import com.wenfs.demo.service.ISysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * shiro权限认证
 *
 * @author wenfs
 */
public class DbRealm extends AuthorizingRealm {

  @Autowired
  private ISysUser iSysUser;
  @Autowired
  private ISysRole iSysRole;
  @Autowired
  private ISysMenu iSysMenu;

  /**
   * shiro登录验证
   * @param authcToken
   * @return
   * @throws AuthenticationException
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    SysUser user = iSysUser.getUserByUserName(token.getUsername());

    //    账号不存在
    if (user == null) {
      throw new AuthenticationException("用户不存在");
    }
    //    账号未启用
    if (user.getUserStatus() == 0) {
      throw new AuthenticationException("用户未启用");
    }

    return new SimpleAuthenticationInfo(user, user.getUserPass(),
            ByteSource.Util.bytes(user.getPassSalt()), this.getName());
  }


  /**
   * shiro权限认证
   * @param principals
   * @return
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    //SimpleAuthenticationInfo的第一个参数
    SysUser user = (SysUser) principals.getPrimaryPrincipal();
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(iSysRole.getRoleCodesByUserCode(user.getUserCode()));
    authorizationInfo.setStringPermissions(iSysMenu.getMenuCodesByUserCode(user.getUserCode()));
    return authorizationInfo;
  }





}
